2010-06-22 140 views
1
  1. 我要選擇從表1,其中有史密斯在列1列2或和狀態1.MySQL的複雜查詢

  2. 如果沒有史密斯在第1列的所有行,然後選擇從價值第2列,如果第2列中有史密斯,則在該行的第1列中選擇值。

  3. 然後,選擇所有從表2的行其包含在列1或表2中的列2該值,(我們得到了通過從表1中選擇)

+0

不是一個複雜但複雜的優化。 – 2010-06-22 06:11:27

回答

0

這應包括#2分之1 ,你已經失去了我#3

select if(col1 = 'smith', col2, col1) from table1 
where (col1 = 'smith' or col2 = 'smith') and status = 1 
0

與本公司查詢

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) 

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) 
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)) 
0

也許是最好的sollution將重新設計你的數據庫, 但如果你真的想保持你的表,你可以試試這個查詢:

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 
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... 

在這一點上我停止能夠理解的問題,因爲從Que問題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);