2010-06-22 5 views
1
  1. Je veux sélectionner toutes les lignes du tableau 1 où il est forgeron colonne1 ou colonne2 et le statut 1.mysql requête complexe avec sélection

  2. S'il est forgeron dans la colonne 1, puis sélectionnez la valeur de colonne 2, et s'il y a smith dans la colonne 2, sélectionnez la valeur dans la colonne 1 de la ligne.

  3. Ensuite, sélectionnez toutes les lignes du tableau 2 qui contient cette valeur dans colonne1 ou colonne2 du tableau 2, (que nous avons obtenu en sélectionnant dans le tableau 1.)

+0

pas complexe mais complexe à optimiser. –

Répondre

0

Cela devrait couvrir # 1/2 , vous me avez perdu aveC# 3

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

avec la requête de 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) 

OU

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

Probablement le meilleur sollution serait de redessiner votre base de données, mais si vous voulez vraiment garder vos tables, vous pouvez essayer cette requête:

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

Quelque chose comme cela pourrait être ce que vous êtes après ...

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

À ce stade, je cesse de pouvoir comprendre la question, comme le retour de Que La première et la deuxième question ne sont pas une valeur mais un ensemble de résultats. Mais il pourrait continuer sur le modèle de ...

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