在MySQL中的其他表查询中选择一个表值

时间:2019-01-09 14:15:03

标签: mysql

我有表格“ printorders”:

id | faktor    | status
1  | 326548768 | 6
2  | 657657875 | 5

我有表格“ delivery”:

id | faktorids 
1  | 326548768-657657875
2  | 876876575-548548534

我要从交货中选择,其中faktorid中的faktor全部等于6 这是我的查询:

SELECT *,
       (
            SELECT status
            FROM printorders
            WHERE faktor = (SUBSTRING(faktorids, 1, 9))
            LIMIT 1
       ) AS d1,
       (
            SELECT status
            FROM printorders
            WHERE faktor = (SUBSTRING(faktorids, 11, 9))
            LIMIT 1
       ) AS d2
FROM delivery
WHERE d1= 6 AND  d2 = 6

但这对我不起作用,哪里出问题了?

2 个答案:

答案 0 :(得分:0)

  

我想从交货中选择所有faktorid中的faktor   等于6

我假设您只想要因子326548768,因为那是唯一一个状态为6的因子?

我相信您或多或少希望此查询,但是很难说没有预期的结果(查询未经测试)。

SELECT 
 printorders__status__6.*
FROM (     
  SELECT 
   printorders.*
  FROM 
   printorders  
  WHERE
   printorders.status = 6

) AS printorders__status__6
INNER JOIN 
 delivery
ON
 FIND_IN_SET(
    printorders__status__6.faktor
  , REPLACE(
        delivery.faktorids
      , '-'
      , ','
   )
)

答案 1 :(得分:-2)

首先,在d2之后您还有一个逗号 ) AS d2, FROM delivery

您的短语也应该看起来像这样

select * from (SELECT *, ( SELECT状态 FROM printorders WHERE faktor = (SUBSTRING(faktorids, 1, 9)) AND status ='requested' LIMIT 1 ) AS d1, ( SELECT status FROM printorders WHERE faktor = (SUBSTRING(faktorids, 11, 9)) LIMIT 1 ) AS d2 FROM delivery) main WHERE d1= 6 AND d2 = 6