问题
What is the best way to get records from the database based on the selected primary keys?
I am able to get the primary keys of the selected (checked) rows from a gridview, and now need to retrieve the corresponding records from the database for those selected compound primary keys.
If the rows are using just one primary key, it would have been easier. I could have just concatenated the primary keys (comma delimited) and use it in a WHERE IN clause. But the rows are using three primary keys (int, int, string)
I am thinking of using an SELECT JOIN (one select for each set of primary keys, then join all selects), but I'm not sure if this is the most optimized way to do this.
What is the best way to handle this?
Thanks in advance.
Niki
[Update] - can't reply to individual comments, I might not have enough priviledges yet, so will update post here to be clear.
Here's an example of what I am doing:
Data coming from one database table with compound key:
TABLE1
KeyCol1 INT (Primary Key),
KeyCol2 STRING (Primary Key),
KeyCol3 INT (Primary Key),
Col4 Decimal,
Col5 STRING,
Other columns . . .
PAGE 1 WITH GRIDVIEW 1:
Sel |KeyCol1 |KeyCol2 |KeyCol3 |Col4 |Col5 |Other Columns . . .
[ ] |100 |CODE1 |01 |10.05 |Description 1 |. . .
[/] |100 |CODE1 |02 | 5.03 |Description 2 |. . .
[ ] |100 |CODE2 |01 |12.45 |Description 4 |. . .
[/] |102 |CODE1 |01 |21.50 |Description 1 |. . .
[/] |102 |CODE2 |01 | 9.10 |Description 5 |. . .
[/] |102 |CODE3 |03 | 7.15 |Description 1 |. . .
. . . (where Sel column is a checkbox, and [/] is checked)
Then after clicking a button (ex. "Cancel Records") on Page 1, I need to get those rows, to display to another page like this:
PAGE 2 WITH GRIDVIEW 2
KeyCol1 |KeyCol2 |KeyCol3 |Col4 |Other Colums |Reason
100 |CODE1 |02 | 5.03 |. . . |_______
102 |CODE1 |01 |21.50 |. . . |_______
102 |CODE2 |01 | 9.10 |. . . |_______
102 |CODE3 |03 | 7.15 |. . . |_______
(where Reason column is a textbox)
回答1:
You can do this in a single query by using adding an OR clause for each trio of ids (i.e. for each selected row in your gridview). For example:
SELECT whatever FROM Table1 WHERE (KeyCol1=val1-1 AND KeyCol2=val1-2 AND KeyCol3=val1-3) OR (KeyCol1=val2-1 AND KeyCol2=val2-2 AND KeyCol3=val2-3) OR .. etc
来源:https://stackoverflow.com/questions/11089170/query-results-based-on-multiple-records-using-compound-primary-key