mysql从一个表中查询多个参数?

时间:2012-10-03 06:59:34

标签: mysql search select

好的,我有mysql查询,我想搜索table_1中的两个参数 我会试着用“php”来表达这个想法

if(table_2_params.params_id == 124){
   //select LIKE  "%EXTEC (Sandvik)%" from  table_2_params.nosaukums
}
elseif(table_2_params.params_id == 126){
  //SELECT  FROM table_2_params WHERE nosaukums is BETWEEN  "2010" AND  "2012"
}

我想查询显示的第一个和第二个参数...(它们都匹配
我希望你能理解我想说的话......

好的,这是 mysql查询:

 SELECT table_1 . * , table_2_params . * 
    FROM table_1, table_2_params
    WHERE table_1.pamat_kat_sad =  '756'
    AND table_1.preces_id = table_2_params.preces_id
    AND (
        (
        table_2_params.params_id =124
        AND table_2_params.nosaukums LIKE  "%EXTEC (Sandvik)%"
        )
        AND (
        table_2_params.params_id =126
        AND table_2_params.nosaukums
        BETWEEN  "2010"
        AND  "2012"
        )
    )
    ORDER BY table_1.preces_id DESC

问题可能是table_2_params.nosaukums类型为longtext ...

如果我只选择

    AND (
    table_2_params.params_id =126
    AND table_2_params.nosaukums
    BETWEEN  "2010"
    AND  "2012"
    )

它显示正确的一年...... 如果我只选择

(
    table_2_params.params_id =124
    AND table_2_params.nosaukums LIKE  "%EXTEC (Sandvik)%"
    )

它还显示正确的值......

但是我不能让他们一起工作..

请帮助我!

谢谢!

2 个答案:

答案 0 :(得分:0)

问题在于:

 AND (
    (
    table_2_params.params_id =124          #remove this check
    AND table_2_params.nosaukums LIKE  "%EXTEC (Sandvik)%"
    )
    AND (
    table_2_params.params_id =126          #or remove this check
    AND table_2_params.nosaukums
    BETWEEN  "2010"
    AND  "2012"
    )
)

你试着比较params_id是124还是126.这将永远不会奏效。删除其中一个比较,您的查询应该工作! :)

答案 1 :(得分:0)

如果您想要两组条件,请使用OR。您还应注意,表之间的连接应使用(INNER|LEFT) JOIN

执行
SELECT
    table_1.*
    , table_2_params.* 
FROM
    table_1
    INNER JOIN table_2_params
        ON table_1.preces_id = table_2_params.preces_id
WHERE
    table_1.pamat_kat_sad =  '756'
    AND
    (
        (
            table_2_params.params_id =124
            AND table_2_params.nosaukums LIKE '%EXTEC (Sandvik)%'
        )
        OR
        (
            table_2_params.params_id =126
            AND table_2_params.nosaukums BETWEEN '2010' AND '2012'
        )
    )
ORDER BY
    table_1.preces_id DESC

最后你的查询可能表现不佳,因为mysql将无法使用AND table_2_params.nosaukums LIKE '%EXTEC (Sandvik)%'的任何索引