我有2个彼此相关的mysql表。第一个表包含postID
和fileID
。第二个表包含postID
,它们与上一个表中的值相同。
我想做的是:
选择postID
等于fileID
的第一个表格中的每个XXX
。现在,对于选定的行,我希望将每个fileID
行减去10000
。
好的,我们说它选择了10行,10 postID
被10000减去了。问题是我想在第二个表中减去相同的postID
。
我在mysql中的新手,我不知道如何处理它。你能救我吗?
答案 0 :(得分:0)
在第一个表中选择fileID等于XXX的每个postID。
SELECT postID FROM table1
WHERE fileID = XXX;
非常简单。
现在,对于选定的行,我想将每个fileID行减去10000。
SELECT postID, (fileID-10000) FROM table1
WHERE fileID = XXX;
假设fileID
是一个数字类型,fileID-10000
也是该类型的有效值(例如,如果它是无符号的,那个值不会是负数),这也是非常简单的
好的,我们说它选择了10行,10个postID被10000减去了。问题是我想在第二个表中减去相同的postID。
好的,您之前正在减去fileID,但我认为您想要的是:
SELECT table1.postID, table1.fileID, table2.postID-10000 FROM table2
INNER JOIN table1 ON table1.postID = table2.postID
WHERE table1.fileID = XXX;
与上述table2.postID
具有相同的限制。
实施例
DROP TABLE IF EXISTS table1;
CREATE TABLE table1 (
postID int,
fileID int
);
DROP TABLE IF EXISTS table2;
CREATE TABLE table2 (
postID int
);
-- Two different postIDs with the same fileID
INSERT INTO table1 VALUES (1, 11), (2, 22), (3, 33), (4, 44), (20, 22);
-- postIDs 2 and 20 match postIDs in table1, which have the same fileID 22
INSERT INTO table2 VALUES (1), (2), (20);
SELECT table1.postID, table1.fileID, table2.postID-10000 FROM table2
INNER JOIN table1 ON table1.postID = table2.postID
WHERE table1.fileID = 22;
这给出了输出:
+--------+--------+---------------------+
| postID | fileID | table2.postID-10000 |
+--------+--------+---------------------+
| 2 | 22 | -9998 |
| 20 | 22 | -9980 |
+--------+--------+---------------------+
正如评论中所述,最终目标是订购包含特定postID
的{{1}}。这也可以使用ORDER BY
语句来完成。例如,
fileID
所有行中的结果,首先排序SELECT table1.postID, table1.fileID
FROM table1
ORDER BY (CASE WHEN fileID = 22 THEN 0 ELSE 1 END);
fileID
的行:
22
答案 1 :(得分:0)
在MySQL中,您可以通过在update语句的表表达式部分中使用连接来更新单个查询中的多个表:
#import "ViewController.h"
@implementation ViewController
-(IBAction)button1:(id)sender {
hellolabel.text = @"hello world";
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[ super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
答案 2 :(得分:0)
您可以使用这样的查询从第二个表中选择与第一个表中选择的postId值对应的postId值,
SELECT * FROM second_table_name
WHERE postId IN (
SELECT postId FROM first_table_name
WHERE fileId=xxx
);
您可以在此选择查询中添加要执行的任何操作。