Consider the following example table:
CREATE TABLE items
(`id` int, `productName` varchar(7), `price_new` decimal(10,2), `price_used` varchar(55))
;
INSERT INTO items
(`id`, `productName`, `price_new`, `price_used`)
VALUES
(1, 'cup', 10.50, 5.50),
(2, 'plate', 9.50, 4.50),
(3, 'mug', 8.50, 3.50)
;
For an application I wish to create a temporary table based on what the user has.
The user would have say a 'cup' with condition of 'new'. (stored in a php array)
My desired temporary table would be something like:
CREATE TEMPORARY TABLE IF NOT EXISTS tempTable (
`id` INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(7) NULL,
`itemCondition` varchar(7) NULL,
`price` decimal(10,2) NULL
);
My question is this:
If I create this temporary table how could I insert 'cup' and 'new' with MySQL selecting the price from the items table based on the itemCondition?
psuedocode:
Insert:
(1, 'cup', (
if itemCondition == 'new'
(select Items.price_new where items.productName = 'cup')
ELSE
(select Items.price_used where items.productName = 'cup')
Thank you for your assistance.
The problem is that until you insert the data into the temptable, sql will not know the value of the imtemCondition field. The value 'new' is supplied in the insert statement itself as a fixed value.
You will need either stored procedure that selects the price based on a parameter value and then insert that price into the temporary table, or you can implement the same logic using php.
Steps:
Provide user id, name, and item condition.
Select the price based on the item condition.
Insert all data to the temporary table.
Related
Is it possible to auto increment column after inserting the same value and also check the duplicate value of maximum of 2 like this:
INSERT INTO info (name, date, sched) VALUES ('$name', '$date', '$sched')
// I want to auto increment for count column after inserting same date and sched
INSERT INTO appointment (date, sched) VALUES ('$date', '$sched')
Here is my table:
Somebody can help me to achieve that or suggest a better way for appointment scheduling? Thanks!
Firstly, table design like this:
create table appointment (
id int(11) unsigned not null auto_increment,
date date not null '2018-01-01',
sched varchar(20) not null defalut '',
count int(11) not null default 0,
primary key (id)
unique key `date_sched` (`date`, `sched`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Then, sql like this:
insert into appointment(date, sched, count) values ($date, $sched, $count)
on duplicate key update count = count + 1
I have the following table:
CREATE TABLE `my_table` (
composite_pk1 INT NOT NULL ,
composite_pk2 INT NOT NULL ,
data VARCHAR(255) NOT NULL ,
primary key (composite_pk1, composite_pk2)
) ENGINE=InnoDB;
For a given composite_pk1, I wish composite_pk2 to act as an autoincrement primary key. I don't wish to lock the table, and as such plan on using a trigger such as the following:
DELIMITER $$
CREATE TRIGGER my_trigger BEFORE INSERT ON my_table
FOR EACH ROW BEGIN
SET NEW.composite_pk2 = (
SELECT IFNULL(MAX(composite_pk2), 0) + 1
FROM issue_log
WHERE composite_pk1 = NEW.composite_pk1
);
END $$
I can now insert a record:
$stmt=$myDB->prepare('INSERT INTO my_table(composite_pk1, data) VALUES (?,?)');
$stmt->execute([123,'hello']);
How do I get the last inserted composite_pk2? PDO::lastInsertId only works with native autoincrement tables (i.e. not the trigger approach). I "could" later do a SELECT query to get the max value, however, there is no guarantee that another record has snuck in.
You can make composite_pk2 an unique key with auto_increment:
CREATE TABLE `my_table` (
composite_pk1 INT NOT NULL ,
composite_pk2 INT NOT NULL unique auto_increment,
data VARCHAR(255) NOT NULL ,
primary key (composite_pk1, composite_pk2)
) ENGINE=InnoDB;
Now last_insert_id() will return the recently created id for composite_pk2.
I have some data to add to my database, I'm not sure what my table schema should be. I have an id number for each specific user, 4 categories of games, and a possible number of items (0+) each user has for each game. I want to set a table for each game with the categories ->id and ->items, so I can save the list of user id's in the table, with the items they have for that game.
I can't seem to get it to work, I think because of the dynamic number of items for each user. Is it possible for me to achieve my above mentioned table schema? Why not/how?
I have been trying:
foreach ($json->rgDescriptions as $mydata)
{
$sql = $dbh->prepare('INSERT INTO user_items_tf2 (items) VALUES (:item) WHERE steam_id = :steamid');
$sql->bindParam(':item', $mydata->name);
$sql->bindParam(':steamid', $steamprofile['steamid']);
$sql->execute();
}
There are numbers of ways to do this but one which is very flexible and seems to answer your questions would be this.
-- Players
CREATE TABLE player
(`id` int primary key auto_increment, `name` varchar(255))
;
-- Games
CREATE TABLE game
(`id` int primary key auto_increment, `name` varchar(255))
;
-- Items and what game they belong to
CREATE TABLE item
(`id` int primary key auto_increment, `game_id` int, `name` varchar(255))
;
-- What games players are playing
CREATE TABLE player_game
(`player_id` int, `game_id` int)
;
-- What items players have
CREATE TABLE player_item
(`player_id` int, `item_id` int, index(`player_id`))
;
If you never needed to ask the question which users had a given item you could skip the player_item table and stuff the data (as JSON for instance) of their items into a column of the player table with a blob type.
$sql = $dbh->prepare('INSERT INTO user_items_tf2 (items, steam_id) VALUES (:item, :steamid)');
Mysql table (migration_terms) fields are as follows
oldterm count newterm seed
I used the following create table statment.
CREATE TABLE `migration_terms`
(
`oldterm` varchar(255) DEFAULT NULL,
`count` smallint(6) DEFAULT '0',
`newterm` varchar(255) DEFAULT NULL,
`seed` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`seed`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
And It works, no problems there.
but then when I used the following insert into statement to populate it;
"INSERT INTO migration_terms
SELECT looseterm as oldterm,
COUNT(seed) AS count
FROM looseterms
GROUP BY looseterm
ORDER BY count DESC "
I get this error;
Column count doesn't match value count at row 1
I cannot figure out why?
If you need the table structure of the looseterms table, it was created by the following create table statement.
CREATE TABLE looseterms
(
`seed` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`looseterm` varchar(255)
)
You need to specify the columns if your select statement has fewer columns than the table
"INSERT INTO migration_terms
(oldterm,
count)
SELECT looseterm AS oldterm,
Count(seed) AS count
FROM looseterms
GROUP BY looseterm
ORDER BY count DESC "
From MySql docs on Insert Syntax
If you do not specify a list of column names for INSERT ... VALUES or
INSERT ... SELECT, values for every column in the table must be
provided by the VALUES list or the SELECT statement. If you do not
know the order of the columns in the table, use DESCRIBE tbl_name to
find out.
Your insert is adding 2 columns of data, whereas your table's definition has 4 columns
I have to construct a table with columns
col1(primary key) col2(not null) col3(not null) col4(not null)
Now I need to insert values into this table such that values inserted into col3 don't repeat for set of values in col2....what are the constraints that is need to implement??...
Values can repeat in col3 as a whole ...But for some set of values of col2 values in col3 need not repeat.
So this is the column name.
ID ID_Category Keywords Score
Values in Keywords column can repeat - but for some values in ID_Category, Keywords values need not repeat.
Can you help me how to implement this??
Using code from http://forge.mysql.com/wiki/Triggers#Emulating_Check_Constraints
First create this general purpose error table
CREATE TABLE `Error` (
`ErrorGID` int(10) unsigned NOT NULL auto_increment,
`Message` varchar(128) default NULL,
`Created` timestamp NOT NULL default CURRENT_TIMESTAMP
on update CURRENT_TIMESTAMP,
PRIMARY KEY (`ErrorGID`),
UNIQUE KEY `MessageIndex` (`Message`))
ENGINE=MEMORY
DEFAULT CHARSET=latin1
ROW_FORMAT=FIXED
COMMENT='The Fail() procedure writes to this table twice to force a constraint failure.';
A generic function created to fail
DELIMITER $$
DROP PROCEDURE IF EXISTS `Fail`$$
CREATE PROCEDURE `Fail`(_Message VARCHAR(128))
BEGIN
INSERT INTO Error (Message) VALUES (_Message);
INSERT INTO Error (Message) VALUES (_Message);
END$$
DELIMITER ;
Now you are armed to create custom constraints on any table, such as yours
DELIMITER $$
create trigger mytable_check before insert on test.mytable for each row
begin
if new.id_category in ('list','of','special','categories')
and exists
(select * from mytable
where id_category=new.id_category
and keywords=new.keywords) then
call fail(concat('id_category,keywords must be unique when id_category is: ',new.id_category));
end if;
end $$
DELIMITER ;