简体   繁体   English

SQL从其他表中选择等级

[英]SQL select rating from other table

i have 2 tables 我有2张桌子

  1. table "users" with column user_id 表“用户”的列user_id
  2. table "extra" with column rating and column user_id 表“额外”的列等级和列user_id

how can i select 2 tables and sorting it by rating? 如何选择2个表格并按评分排序?

my query 我的查询

SELECT
   USER_ID,
   SUM(RATING) 
FROM
   USERS,
   EXTRA 
WHERE
   EXTRA.USER_ID = '{$row['USER_ID']}'

Column ' user_id ' in field list is ambiguous user_id ”在字段列表是不明确

Never use commas in the FROM clause. 请勿FROM子句中使用逗号。 Always use proper explicit JOIN syntax. 始终使用正确的显式JOIN语法。

Apart from that, the query is over complicated. 除此之外,查询过于复杂。 You only need to reference once table: 您只需要引用一次表:

SELECT e.USER_ID, SUM(e.RATING) 
FROM EXTRA e
WHERE e.USER_ID = '{$row['USER_ID']}';

Additional notes: 补充笔记:

  • Provide table aliases for table names, typically the abbreviate of the table name. 提供表名的表别名,通常是表名的缩写。 This makes queries easier to write and to read. 这使查询更易于编写和阅读。
  • Qualify all column names in the query. 限定查询中的所有列名称。
  • Do not munge query strings with parameter values. 不要用参数值来修饰查询字符串。 SQL provides parameter placeholders for exactly this purpose. SQL为此提供了参数占位符。

So the query should look more like: 因此查询应更像:

SELECT e.USER_ID, SUM(e.RATING) 
FROM EXTRA e
WHERE e.USER_ID = ?

Both of your tables have user_id column. 您的两个表都有user_id列。 You must specify which one you want to select: 您必须指定要选择的一个:

SELECT users.user_id, SUM(rating) FROM users, extra WHERE extra.user_id ='{$row['user_id']}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM