简体   繁体   English

MySQL - 结合INSERT,VALUES和SELECT?

[英]MySQL - Combining INSERT, VALUES, and SELECT?

I'm kind of new to SQL, and I'm really only interacting with it enough to get a high score database working. 我对SQL很陌生,我真的只是与它进行交互以获得高分数据库的工作。 I'm using a php script to access my online MySQL db. 我正在使用php脚本访问我的在线MySQL数据库。 Anyways. 无论如何。

What I have is 2 tables, Player and Score. 我所拥有的是2桌,球员和得分。 Player has an id, uniqueDeviceId, and chosenname. 播放器具有id,uniqueDeviceId和selectedname。 Score has the usual things youd expect. 分数具有您期望的常规事物。

What I'd really like to do in a single query (to reduce complexity...) is to combine the syntaxes of 我在单个查询中真正想要做的是(为了降低复杂性......)是结合使用的语法

INSERT INTO scores VALUES
and INSERT INTO scores SELECT...

Into some sort of monster, like 变成某种怪物,就像

INSERT INTO scores(score,difficulty,playerid)
   VALUES(TheScoreThatImProviding,TheDifficultyThatImProviding, (SELECT 
       id FROM player WHERE uniqueDeviceId = TheUniqueIdThatImProviding)
     )

If that makes sense. 如果这是有道理的。 I want to lookup the playerId (3rd "value"), and mix the result of that select with the input of the VALUES provided. 我想查找playerId(第三个“值”),并将该选择的结果与提供的VALUES的输入混合。

Is this possible? 这可能吗? All the googling results ive found either have it all VALUES or all SELECT. 所有的谷歌搜索结果我发现要么全部有VALUES或所有SELECT。

Makes sense and is called INSERT SELECT . 有道理并被称为INSERT SELECT This is an example query for the uniqueDeviceId 123, Score 5 and Difficulty 'easy': 这是uniqueDeviceId 123,Score 5和Difficulty'easy'的示例查询:

INSERT INTO scores (score, difficulty, playerid)
  SELECT 5, 'easy', id
  FROM player WHERE uniqueDeviceId = 123;

According to this page you're close. 根据这个页面,你很接近。 But put all the values into your select. 但是将所有值都放入您的选择中。 Something like: 就像是:

insert into scores (score, difficulty, playerid )
    select TheScoreThatImProviding, TheDifficultyThatImProviding, player.id 
      from player where uniqueDeviceId = TheUniqueIdThatImProviding

What about this approach: 这种方法怎么样:

INSERT INTO `tableA` SET 
           columnA =  (SELECT `columnY` FROM `tableY` WHERE `id` = 2), 
           columnB =  (SELECT `columnZ` FROM `tableB` WHERE `id` = 3);

I didn't benchmarked it yet. 我还没有对它进行基准测试。 But using multiple SELECT statements will burden the Database server. 但是使用多个SELECT语句会给数据库服务器带来负担。 The plus side of this approach is the readability. 这种方法的优点是可读性。

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

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