选择所有行,其中id = id,另一列=具有该ID的另一列

时间:2019-02-27 16:28:47

标签: mysql sql join select union

大家好,我想

 SELECT * rows WHERE id = (for example) 123.

此外,我想从123行中选择列favorite_number,然后选择id = 123的所有WHERE id = favorite_number。我该怎么做?

这是我到目前为止所拥有的:

SELECT * FROM users WHERE (id = :id) OR (id = :id AND get favorite_number from that row and search for it as ID);

示例:选择ID = 123的所有行。此外,如果该行的列favorite_number不为空且不等于0,则选择favorite_number(在此示例中,数字为456 ),然后搜索相同的表:WHERE id = 456。

如何在一个搜索查询中完成所有操作?我希望这已经足够清楚了,谢谢!

4 个答案:

答案 0 :(得分:0)

您可以使用自连接;

SELECT * -- You should always explicitly select the columns rather than *
FROM    users us
LEFT JOIN users uf
         ON uf.Id = us.favorite_number
WHERE us.id = 123

很显然,如果需要,您可以更改为内部联接,并在where条件(或join条件)中添加更多内容。

答案 1 :(得分:0)

Select * From Users Where Id = 123 Or Id in
(Select favorite_number From Users Where Id = 123 And favorite_number Is Not Null And favorite_number <> 0)

答案 2 :(得分:0)

似乎您正在同一行但在不同列中查找这两种情况 这样,您应该添加一个AND条件,扩展到

SELECT * 
FROM users 
WHERE id = :id
AND favorite_number = :id ;

答案 3 :(得分:0)

我假设您需要1或2行,并且可以使用UNION进行操作:

select * from tablename
where id = 123
union all
select * from tablename
where id = (
  select favorite_number from tablename where id = 123
)

如果favorite_numbernull0,则第二个查询将不会获取任何内容。