简体   繁体   English

MySQL选择在WHERE IN()中使用

[英]MySQL Select Use in WHERE IN()

Hello to Everyone. 大家好

I have two table, for example; 例如,我有两个表。

TABLE Name X 表格名称X

________________
| id |    A    | 
|____|_________|
| 1  | 1,2,4,8 |
|____|_________|

This Query is working in another TABLE Y, 此查询在另一个表Y中工作,

    mysql_query(" Select * from Y where id IN(1,2,4,8) ")

But this in not working, 但这无法正常工作

    mysql_query(" Select * from Y where id IN(Select A from X where id=1) ")

What can I do? 我能做什么? Thank You. 谢谢。

A better table design would be: 更好的表设计将是:

table X:
--------
id int
someid int

Values in the table would be: 该表中的值为:

id  someid
--  --------
1   1
2   1
4   1
8   1

Your query could then be mysql_query(" Select * from Y where id IN(Select id from X where someid=1") . 然后,您的查询可能是mysql_query(" Select * from Y where id IN(Select id from X where someid=1")

To answer your question -- You appear to be querying from PHP or something similar. 回答您的问题-您似乎正在从PHP或类似的工具查询。 Using the table structure you have, you could retrieve the value from table X using mysql_query("Select A from X where id=1") and store the results in a variable. 使用现有的表结构,您可以使用mysql_query("Select A from X where id=1")从表X中检索值,并将结果存储在变量中。 You could then execute a second query, mysql_query(" Select * from Y where id IN(" + yourVar + ") ") . 然后,您可以执行第二个查询, mysql_query(" Select * from Y where id IN(" + yourVar + ") ")

This is a "Has Many" relationship, so you should have an intermediate join table. 这是一个“很多”关系,因此您应该有一个中间联接表。 The benefit to this structure is on insertions and deletes. 这种结构的好处在于插入和删除。 In your structure to append or delete from A you'd have you pull the record, change the value and write it back (or write a procedure maybe). 在要从A追加或删除的结构中,您需要拉记录,更改值并将其写回(或写一个过程)。

    X       
_________
|  id   |
|_______|
|  1    | 
|_______|               

    Y
_________
|  id   |
|_______|
|  1    | 
|_______|   
|  2    | 
|_______|   
|  3    | 
|_______|   

    X_Y
____________________________
|  id   |  x_id  |    y_id |
|_______|________|_________|
|  1    |   1    |    1    |
|_______|________|_________|  
|  2    |   1    |    2    |
|_______|________|_________|
|  3    |   1    |    3    |
|_______|________|_________|


SELECT * FROM Y INNER JOIN X_Y ON Y.id=X_Y.y_id WHERE X_Y.x_id=1

or

SELECT * FROM Y WHERE id IN (SELECT y_id FROM X_Y WHERE x_id=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM