我想从表1中选择所有行。在column1或column2和状态1中有smith。
如果第1列中有smith,则从第2列中选择值,如果第2列中有smith,则在行的第1列中选择值。
然后选择表2中的所有行,其中包含表2的column1或column2中的值(我们通过从表1中选择得到的。)
答案 0 :(得分:0)
这应该涵盖#1/2,你已经失去了#3
select if(col1 = 'smith', col2, col1) from table1
where (col1 = 'smith' or col2 = 'smith') and status = 1
答案 1 :(得分:0)
与Ben的查询
select * from table2
where column1 in (select if(column1 = 'smith', column2, column1) from table1 where (column1 = 'smith' or column2 = 'smith') and status = 1)
OR
column2 in (select if(column1 = 'smith', column2, column1) from table1 where (column1 = 'smith' or column2 = 'smith') and status = 1)
OR
select * from table2 where
column1 in (select column1 from table1 where column2 = 'Smith' AND status = 1) OR
column1 in (select column2 from table1 where column1 = 'Smith' AND status = 1) OR
column2 in (select column1 from table1 where column2 = 'Smith' AND status = 1) OR
column2 in (select column2 from table1 where column1 = 'Smith' AND status = 1)
答案 2 :(得分:0)
select *
from table1 as t1, table2 as t2
where t1.status = 1
and (t1.col1 = 'smith' and (t2.col1 = t1.col2 or t2.col2 = t1.col2)
or t1.col2 = 'smith' and (t2.col1 = t1.col1 or t2.col2 = t1.col1))
答案 3 :(得分:0)
可能最好的解决方案是重新设计数据库, 但如果你真的想保留你的表,你可以尝试这个查询:
SELECT IF(t1.col1 = 'smith', t1.col2, t1.col1) AS t1col2, IF(t2.col1 = t1col2, t2.col2, t2.col1) AS t2col2
FROM table1 AS t1
JOIN table2 AS t2 ON( IF(t1.col1 = 'smith', t1.col2, t1.col1) IN ( t2.col1, t2.col2 ) )
WHERE (t1.col1 = 'smith' OR t1.col2 = 'smith') AND t1.status = 1
答案 4 :(得分:0)
这样的事情可能就是你所追求的......
SELECT *
FROM table_1
WHERE col_1 LIKE '%smith%' AND status = 1
UNION DISTINCT
SELECT *
FROM table_1
WHERE col_2 LIKE '%smith%' AND status = 1
UNION
SELECT *
FROM table_2
WHERE ...er...
此时我不能理解这个问题,因为问题1和问题2的回报不是值而是结果集。但它可以继续......
WHERE col_1 IN (SELECT col_1
FROM table_1
WHERE col_1 LIKE '%smith%' AND status = 1
UNION
SELECT col_2
FROM table_1
WHERE col_2 LIKE '%smith%' AND status = 1);