This question already has answers here:
MySQL query finding values in a comma separated string
(11 answers)
Closed 6 years ago.
I have a table named 'offers' that has a column in_stores. It contains the ids of the stores that this offer is available in. Graphically this table looks like this:
id | title | in_stores
1 | Shoes | 1002,1003
2 | Gloves | 1020,1011
3 | Shades | 1002,1009
4 | Hats | 1010,1002
5 | Shoes | 1220
6 | Shirts | 1010
7 | Hats | 1002
Each value in in_stores is saved with the implode() function through PHP.
My question:
How to select in a single mysqli query all the offers that are available in a store with id 1002. In this example the query should return offers with id 1,3,4,7. I guess I should use something like explode() first to get the results in an array and than in_array() to search for the specific id in it but all those functions are unavailable within SQL.
This is a major issue with storing comma separated fields.
MySQL does have a function to allow searching for these, and this will be a lot more reliable than trying to rely on using LIKE. But as it still cannot effectively use any index it will not be fast.
SELECT *
FROM offers
WHERE FIND_IN_SET('1002', in_stores)
Far better to redesign your database to use an extra table with a row for each value for each id.
You "could" do it with a LIKE Query, but this is not recommended.
SELECT * FROM offers WHERE in_stores LIKE "%1002%".
As long as you don't have values bigger than 9999 this will work.
BUT when one of your stores has the id 11002 of 99991002 it will also return these unwanted values.
What you should do is transform your mysql table to a have a second table storeLocations or sth. else. This should only have the properties offer_id and store_id.
It will transform your data to:
`offers`
id | title
1 | Shoes
2 | Gloves
3 | Shades
4 | Hats
5 | Shoes
6 | Shirts
7 | Hats
`storeLocations`
offer_id, store_id
1 | 1002
1 | 1003
2 | 1020
2 | 1011
3 | 1002
3 | 1009
4 | 1010
4 | 1002
5 | 1220
6 | 1010
7 | 1002
Then you can select from it like
SELECT * FROM offers AS o
LEFT JOIN storeLocations as l ON (o.id=l.offer_id)
WHERE l.store_id = 1002;
Now when you insert data you don't have to use implode but insert as many rows into storeLocations as there are store_id's for that specific item.
For more info on that topic have a look here.
I think you should be using the MySQL LIKE operator. It searches the database column for strings specified in your query.
Try this query:
$sql = "SELECT * FROM offers WHERE in_store LIKE '%1002%'";
Check this link for more explanation: W3Schools - SQL LIKE Operator
I think that should do the trick.
Related
I have four tables. The first describing a mix of items. The second is a linking table between the mix, and the items. The third is the item table, and the fourth holds lot information - lot number, and when that lot starts being used.
mix
mixID | mixName
----------------
1 | Foxtrot
2 | Romeo
mixLink
mixID | itemID
----------------
1 | 1
1 | 2
1 | 3
item
itemID| itemName
----------------
1 | square
2 | triangle
3 | hexagon
itemLots
itemID| lotNo | startDate
-------------------------
1 | 22/5/3| 22/07/16
2 | 03/5 | 25/07/16
2 | 04/19 | 12/08/16
3 | 15/0 | 05/08/16
Now, I need to be able to fetch the information from the database, which details all the items from a mix, as well as the most recently used lot number, something like this:
itemName | lotNo
----------------
square | 22/5/3
triangle | 04/19
hexagon | 15/0
I've tried a dozen different mixes of joins, group by's, maxes, subqueries, and havings; all to no avail. Any help would be much appreciated, I've been pulling my hair out for hours, and I feel like my fingernails are just scraping at the solution!
This will give you the result you're after and will perform pretty well if you have your indexes done properly. I'm not sure how you're meaning to reference mix as it's not apparent in your sample output but I've included it in the WHERE clause so hopefully you can understand where you would use it.
SELECT i.itemName
, (SELECT il.lotNo FROM itemLots il
WHERE il.itemID=i.itemID
ORDER BY il.startDate desc
LIMIT 1) as lotNo
FROM item i
JOIN mixLink ml ON ml.itemID=i.itemID
JOIN mix m ON m.mixID=ml.mixID
WHERE m.mixName="Foxtrot";
This question already has answers here:
mysql unique number generation
(9 answers)
Closed 8 years ago.
I am wondering if there is any way to generate the random five digit number and insert into database using mysql. I know i can do it using PHP but wanted to know if i can get rid of the php and do it using database. Also, the generated number should be different than the numbers already stored in the database.
Following is example as how it should look like:
I have four letters of pattern common in random_no field which is org1 and want to append other 5 random letters as shown in following example:
+-------+-----------+-----------+--------------------------------------------+
| id | title | phone | ABN | Random No |
+-------+-----------+----------+---------------------------------------------
| 1 | title1 | 4765 5678 | 214-444-1234 | org123456 |
| 2 | title2 | 4444 4444 | 555-111-1234 | org109876 |
| 3 | title3 | 3333 3333 | 214-222-1234 | org187654 |
| 4 | title4 | 1111 1111 | 817-333-1234 | org156432 |
| 5 | title5 | 2222 2222 | 214-555-1234 | org177654 |
+-------+-----------+-----------+--------------------------------------------
Any help will be appreciated.
Now there is no guarentee that there are not going to be duplicates... but this is getting two random numbers and multiplying them by different numbers so its not all that likely that they will be getting random numbers
UPDATE table t,
( SELECT id, LPAD(FLOOR(7 + (RAND() * 50) * (RAND() * 333)), 5, 0) as join_num
FROM table
)t1
SET t.random_no = CONCAT(t.random_no, t1.join_num)
WHERE t.id = t1.id;
From here I recommend you do this.. after updating your table go back through and run this query
SELECT id FROM table
GROUP BY random_no
HAVING COUNT(*) > 1;
if there are any results returned then the id's there will need a different random number and you can just change it at any duplicate spots once you know if there are any dupes
Breakdown of the update query....
update the table alias t.
select from table the id and then the random number alias t1.
concat the number and the column by row..
where the id's are equal... getting a different number for each row.
LPAD is a zero fill so that way if the number is smaller than 5 spaces it'll fill it in with 0's and then you have to use FLOOR() with RAND() for the random number.
Hope thats helpful!
I am trying to generate fixtures for a sports website. I have a table called Members, with relevant columns being member_id and league_id. The league_id will be passed from a form on the previous page as the variable $leagueid.
I'm pulling out all the member ID's relating to that league ID using...
$result = mysql_query("SELECT member_id FROM Members WHERE league_id = '$leagueid'")
I now need to generate fixtures for all these member ID's and then insert that data into the MySQL table 'Fixtures'. Each row of data in that table needs to include:-
player1 - member_id of the first player
player2 - member_id of the second player
week - integer showing which week the match will be played
league_id
However, there are some special conditions that also need to be applied.
Every 3rd week needs to remain free (i.e. weeks 3,6,9,12 etc). No matches can be scheduled on these weeks
There needs to be an option (which will be selected and passed from a form on the previous page as a checkbox variable called $double) which will double up the matches. This means that after generating one complete round of fixtures, you need to take the generated list, swap ID's for players 1 and 2, and duplicate them all. So 1 round of fixtures could look like this....
Week 1
1 vs 2
3 vs 4
Week 2
1 vs 3
2 vs 4
Week 3
1 vs 4
2 vs 3
Then you would swap the ID's and add on another set...
Week 4
2 vs 1
4 vs 3
Week 5
3 vs 1
4 vs 2
Week 6
4 vs 1
3 vs 2
What I'm looking for is some code that will generate all these fixtures while keeping in mind all the special conditions that I've listed.
I know this is all possible in PHP but I also think I can do it using one SQL query instead, which might be a lot cleaner. Can anyone help me out?? Thanks!!
P.S. I know I'm using mysql and not mysqli. I am currently trying to transfer over to mysqli but I'm having some problems which I have posted on a separate question that I have yet to get a correct answer to.
SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+
SELECT * FROM ints WHERE MOD(i,3) > 0;
+---+
| i |
+---+
| 1 |
| 2 |
| 4 |
| 5 |
| 7 |
| 8 |
+---+
The second part is simply
INSERT INTO my_table SELECT week_id+3, column_2, column_1 FROM my_table;
I have two tables in my database
table: products table: companies
+-----------+------------+ +------+------------+
| name | company_id | | id | name |
+-----------+------------+ +------+------------+
|Product 1 | 1 | | 1 | Company 1 |
|Product 2 | 1 | | 2 | Company 2 |
|Product 3 | 3 | | 3 | Company 3 |
|Product 4 | 1 | | 4 | Company 4 |
|Product 5 | 1 | | ... |
|Product 6 | 3 | +------+------------+
|Product 7 | 2 |
|... |
+-----------+------------+
Now I have to make company-selector (filtering products by company) using HTML SELECT element with names of all companies from table companies and COUNT of products after company name in the list.
So, my goal is to get SELECT options like this:
Company 1 (4)
Company 2 (1)
Company 3 (2)
Company 4 (0)
(note: counts inside the brackets are from example above)
What have I tried so far?
I was using mysql_* functions earlier and later it was mysqli procedural model. I can do this manually with one query for companies and another one inside while block to get COUNT of elements (filtered by current company's id in the loop). Now I'm trying to work with PDO object which is something new for me and I'm not very familiar with it.
Question
Is it somehow possible to get COUNT with one query (using JOINs or something)? If not, how I can do it with query inside the loop (old way) using my $dbPDO object? Or any other way?
I've looked some examples here but nothing could adapt to fit my requirements. Maybe I missed something but working with PDO is still painful for me (and I must learn it ASAP).
Looking at my own question, I don't think it's something hard, but the worst thing, I can't find solution by myself.
At the end, I have solution in mysqli, just I don't like it so much and think there's easier way of making this task done!
I thought this question is something I need but still don't understand that query in answer.
So far I have this code and have no idea how to make it counts products:
$dbPDO = new PDO('mysql:dbname=comixdb;host=localhost', 'root', '');
$sel_cat = ''; # selector HTML
$sql = "SELECT * FROM categories ORDER BY name";
foreach ($dbPDO->query($sql) as $row) {
$sel_cat .= "<option value=\"{$row['id']}\">{$row['name']}</option>";
}
$sel_cat = "<select><option value=\"*\">All categories</option>$sel_cat</select>";
echo $sel_cat;
Hope I've clarified question enough. Any help would be appreciated.
What you need can be done in SQL:
SELECT companies.name, SUM(IF(company_id IS NULL, 0, 1)) AS products
FROM companies
LEFT JOIN products ON (companies.id = products.company_id)
GROUP BY companies.id;
The LEFT JOIN ensures that all companies get selected, and the SUM ensures that the count is correct (a simple COUNT would return 1 for companies with no products).
I have a comma delimited list that im storing in a varchar field in a mysql table.
Is it possible to add and remove values from the list directly using sql queries? Or do I have to take the data out of the table, manipulate in PHP and replace it back into mysql?
There is no way to do it in InnoDB and MyIsam engines in mysql. Might be in other engines (check CSV engine).
You can do it in a stored procedure, but, not recommended.
What you should do to solve such an issue is to refactor your code and normalize your DB =>
original table
T1: id | data | some_other_data
1 | gg,jj,ss,ee,tt,hh | abanibi
To become:
T1: id | some_other_data
1 | abanibi
T2: id | t1_id | data_piece
1 | 1 | gg
2 | 1 | jj
3 | 1 | ss
4 | 1 | ee
5 | 1 | tt
6 | 1 | hh
and if data_piece is a constant value in the system which is reused a lot, you need to add there a lookup table too.
I know it looks more work, but then it will save you issues like you have now, which take much more time to solve.