一个SQL中的两个表,查询

时间:2016-05-22 21:18:45

标签: php mysql select sql-order-by

我有两张桌子

 ID_USER | USERNAME
   1       Max
   2       Jean
   3       Carl
   4       Sophie

ID_MONEY | ID_USER | MONEY
  1           4      1000
  2           2      1500
  3           3      1250
  4           1      920

我想执行第二个表SQL并按用户名(按字母顺序)对结果进行排序,以获得此结果:

Carl have: 1250$
Jean have: 1500$
Max  have: 920$
Sophie have: 1000$

我应该执行什么类型的查询? 我试过了,

SELECT * 
FROM $table_users 
WHERE id_user='$id_user' 
ORDER BY (SELECT username FROM $table_money WHERE id_user='$id_user') ASC 

但不是预期的结果。

3 个答案:

答案 0 :(得分:1)

您需要INNER JOIN。这可以使用连接或WHERE子句来完成。

SELECT USERNAME, MONEY
FROM $table_users
JOIN $table_money USING (ID_USER)
ORDER BY USERNAME

SELECT USERNAME, MONEY
FROM $table_users, $table_money
WHERE $table_users.ID_USER = $table_money.ID_USER
ORDER BY USERNAME

答案 1 :(得分:0)

我猜table_money可能会为同一个用户提供多个货币值,您可能需要总数。

SELECT table_users.ID_USER, table_users.USERNAME, SUM(table_money.MONEY)
FROM table_users  INNER JOIN table_money ON table_users.ID_USER = table_money.ID_USER
GROUP BY table_users.ID_USER, table_users.USERNAME
ORDER BY table_users.USERNAME

答案 2 :(得分:0)

在这里,我使用连接函数来连接字符串。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
      <div class="container">
        <div class="row">
          <div class="col-xs-12 col-md-4">
            <button type="button" class="btn btn-block" aria-label="center Align">
              <a href="pricing.html" target="_blank">
                <h4>Header 4</h4>
                <p><strong>£££</strong><span>/ £££ a month</span></p>
                <ul>
                  <li> Text </li>
                  <li> Text </li>
                  <li> Text </li>
                  <li> Text </li>
                </ul>
              </a>
            </button>
          </div>

          <div class="col-xs-12 col-md-4">
            <button type="button" class="btn btn-block" aria-label="center Align">
              <a href="pricing.html" target="_blank">
                <h4>Header 4</h4>
                <p><strong>£££</strong><span>/ £££ a month</span></p>
                <ul>
                  <li> Text </li>
                  <li> Text </li>
                  <li> Text </li>
                  <li> Text </li>
                </ul>
              </a>
            </button>
          </div>

          <div class="col-xs-12 col-md-4">
            <button type="button" class="btn btn-block" aria-label="center Align" disabled>
                <h4>Header 4</h4>
                <p><strong>£££</strong><span>/ £££ a month</span></p>
                <p id="tempBottom"><strong>Coming Soon</strong></p>
            </button>
          </div>
        </div>
      </div>
    </div>

输出: -

enter image description here