# SQL Select inside Insert

**URL:** <https://community.unix.com/t/sql-select-inside-insert/211869>\
**Category:** Web Development\
**Created:** [September 9, 2008, 5:25pm UTC](https://community.unix.com/t/sql-select-inside-insert/211869 "2008-09-09T17:25:39Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ikon](https://community.unix.com/user_avatar/community.unix.com/ikon/32/1015_2.png) [@Ikon](https://community.unix.com/u/Ikon)\
**Post date:** [September 9, 2008, 5:25pm UTC](https://community.unix.com/t/sql-select-inside-insert/211869/1 "2008-09-09T17:25:39Z")

</div>

I have following.

```nohighlight
.
.
.
$userid = 2
.
$query = "select username from users where userid = ".$userid.";";
.
$username = $line['uid'];
$data="Some Data Here";
.
$query = "insert into logger (username, data) valuse ($username, $data);";
.
 

```

I would like to not have 2 database calls.

Im sure there is a way to "join" the 2. I want to store the actual username in the logger table and not the UID#, I have not had much luck.

Probabally something really easy im missing.

Something like this:

```nohighlight
insert into logging 
('type','who','data','ipaddress') 
values 
("testing", (select username from users where id = 2;), "data here","1.1.1.1");

```

Thanks...

---

<div class="post-metadata">

**Author:** ![Ikon](https://community.unix.com/user_avatar/community.unix.com/ikon/32/1015_2.png) [@Ikon](https://community.unix.com/u/Ikon)\
**Post date:** [September 9, 2008, 5:45pm UTC](https://community.unix.com/t/sql-select-inside-insert/211869/2 "2008-09-09T17:45:11Z")

</div>

I figured it out...

```nohighlight
insert into logging 
(type,who,data,ipaddress) 
values 
("testing",(select username from users where id = 2),"data here","1.1.1.1");

```

Was using wrong quotes.

---

<div class="post-metadata">

**Author:** ![cbkihong](https://community.unix.com/letter_avatar/cbkihong/32/6_449c533f586939b6e5f246632a46421f.png) [@cbkihong](https://community.unix.com/u/cbkihong)\
**Post date:** [September 11, 2008, 11:10am UTC](https://community.unix.com/t/sql-select-inside-insert/211869/3 "2008-09-11T11:10:17Z")

</div>

In MySQL there is a INSERT ... SELECT that you can probably use to avoid a subquery, but you didn't confirm whether you were using MySQL. Not sure about other database engines though.

---

<div class="post-metadata">

**Author:** ![Ikon](https://community.unix.com/user_avatar/community.unix.com/ikon/32/1015_2.png) [@Ikon](https://community.unix.com/u/Ikon)\
**Post date:** [September 11, 2008, 11:21am UTC](https://community.unix.com/t/sql-select-inside-insert/211869/4 "2008-09-11T11:21:33Z")

</div>

Yes I am using MySQL v5.0.45
