String1 - result1 - string2 - result2

时间:2016-02-22 16:36:41

标签: mysql

所以我需要找出一个可能会打印一个句子的查询,如下例所示:

  

"最昂贵的项目是Apple,最便宜的项目是LG"

Example table: 
+---------+-------+---------+
|  item   | price | inStock |
+---------+-------+---------+
| Samsung |    55 |      40 |
| Apple   |    80 |      45 |
| LG      |    45 |      25 |
+---------+-------+---------+

这是我到目前为止所做的,但我打印出来的是给我这个:

SELECT GROUP_CONCAT('The most expensive item is ', item SEPARATOR ' and the
cheapest item is ') 
FROM table_name 
WHERE price=(SELECT MAX(price) FROM table_name) OR price=(SELECT MIN(price) FROM table_name) 
GROUP BY 'all';
  

"最昂贵的项目是Apple,最便宜的项目是,最多   昂贵的物品是LG,最便宜的物品是"

2 个答案:

答案 0 :(得分:2)

尝试此查询:

SELECT CONCAT('The most expensive item is ',
    (SELECT item
    FROM yourTable
    WHERE price = (SELECT MAX(price) from yourTable)),
    ' and the cheapest item is ',
    (SELECT item
    FROM yourTable
    WHERE price = (SELECT MIN(price) from yourTable)))

答案 1 :(得分:1)

试试这个:

SELECT CONCAT('The most expensive item is ', 
              GROUP_CONCAT(item ORDER BY price DESC 
                           SEPARATOR ' and the cheapest item is ') )
FROM table_name 
WHERE price=(SELECT MAX(price) FROM table_name) OR 
      price=(SELECT MIN(price) FROM table_name)

当遇到关系时,此查询当然不起作用。

Demo here