How to weigh terms alphabetically

MySQL and Drupal

Following on from my Numbering Rows in MySQL article, today I needed to populate the weight column of the term_data table for about a hundred terms so that they incremented in alphabetical order. This was, on the face of it, a very tedious task; click edit, select weight from drop-down, submit, 'goto 1'.

As I said in my Numbering Rows in MySQL article, I don't like tedious - but I do like over-complicated methods which actually make my life more interesting and less tedious... Enter a nifty MySQL script!

This is basically the same as the Numbering Rows in MySQL tip, except this works on the term_data table instead of menu. Its defines a variable and updates the table, setting the weight to the variable value before incrementing it.

SET @cnt = 0;
 
UPDATE term_data
SET weight = @cnt := (@cnt+1)
WHERE vid=2
ORDER BY name;

If you use SQLyog, as I do, you must hit the button to Execute All Queries (the double green arrow, or Shift+F5 for the shortcut-minded ones). If you don't do this you end up sitting there like a lemon for a few minutes wondering why no rows are being updated.

I might be tempted in the future to turn this into a module where you can set all the weights for terms in a given vocabulary based on an alphabetical order.

Comment Icon

1 Comments

The most recent comment was on Sat, 11th Aug 2007 - 05:22

Very good

Add new comment

Filtered HTML

  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd> <img> <p>
  • You can use BBCode tags in the text. URLs will automatically be converted to links.
  • You can enable syntax highlighting of source code with the following tags: <code>, <pre>, <bash>, <css>, <html>, <js>, <jquery>, <mysql>, <php>. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.