MySQL查询-带有子查询结果的where子句

时间:2018-08-24 13:30:29

标签: mysql

这个查询让我很沮丧,我已经解决了许多小时:(

SELECT m_order.id,       
 (SELECT SUM(price*amount) FROM m_order_item as item WHERE item.id_order = m_order.id) AS total
FROM `m_order` 
WHERE total > 100

它会不断地在未知列'total',但结果是没有问题的名称为“ total”的where子句列完全可以计算出来。

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

您不能在JOIN子句中使用别名。请参见manual。将其放入UNION

<!-- Display div -->
<div id="PRJNA252931" class="invisible" style="position: absolute; top: 60px; right: 50px; background-color: #f1f1f1; width: 480px; height:190px; padding: 10px; border: #0000cc 2px solid; border-radius: 5px; overflow:auto;">
    <?php
        $file = "PRJNA252931";

        // Here we add a button that calls loadFile() when it is clicked, function parameters are the button element itself and the file URL we want to download
        $content = "
            <code>
                <button onclick='loadFile($(this), \"layout/files/Project_Detail/".$file."\");'
            </code>
        ";

        echo $content;
    ?>
</div>

<!-- JavaScript -->
<script>
    function loadFile(btn, file)
    {
        // Use Fetch API to get the file, then replace the button we click with the contents of that file
        fetch(file).then((resp) => resp.text()).then(function(data) {
            btn.replaceWith(data);
        });
    }
</script>

答案 1 :(得分:1)

total是列别名,对于where条件.. where part由bd引擎在选择select子句之前进行评估

是不可见的

所以您应该重复代码

SELECT m_order.id,       
 (  SELECT SUM(price*amount) 
    FROM m_order_item as item 
    WHERE item.id_order = m_order.id ) AS total
FROM `m_order` 
WHERE  (  SELECT SUM(price*amount) 
    FROM m_order_item as item 
    WHERE item.id_order = m_order.id ) > 100

或尝试使用 已过滤选择

的结果
  SELECT m_order.id,       
   (  SELECT SUM(price*amount) 
      FROM m_order_item as item 
      WHERE item.id_order = m_order.id ) AS total
  FROM `m_order` 
  HAVING  total >  100